package com.itzzj.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.itzzj.common.anno.OperateLog;
import com.itzzj.common.enums.ActionEnum;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 图片验证码接口类
 */
@Api(tags = "图片验证码接口类")
@Slf4j
@RestController
@RequestMapping("/verificationCode")
public class KaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    /**
     * 获取图片验证码
     * @param response
     * @return
     */
    @OperateLog(desc = "获取验证码",actionType = ActionEnum.GET_CODE)
    @GetMapping("/getImageCode")
    public void getImageCode(HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setHeader("Cache-Control","no-cache");
        response.setHeader("Pragma","no-cache");
        response.setContentType("image/jpeg");
        String code = defaultKaptcha.createText();
        log.info("验证码：{}",code);
        // 创建验证码图片
        BufferedImage image = defaultKaptcha.createImage(code);
        ServletOutputStream os = response.getOutputStream();
        // 输出图片到前端
        ImageIO.write(image,"jpg",os);
    }

}










































